package com.gewu.pm.ui.activity.sales;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.gewu.pm.R;
import com.gewu.pm.aop.SingleClick;
import com.gewu.pm.app.AppActivity;
import com.gewu.pm.http.glide.GlideApp;
import com.gewu.pm.other.IntentKey;
import com.gewu.pm.ui.activity.ImageSelectActivity;
import com.gewu.pm.ui.dialog.SelectSubmitterDialog;
import com.gewu.pm.ui.dialog.SelectionListDialog;
import com.gewu.pm.ui.dialog.TipsTwoDialog;
import com.gewu.pm.utils.TextStarUtils;
import com.hjq.base.BaseDialog;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 转终端页面
 * 
 * 功能：
 * 1. 展示线索基本信息
 * 2. 选择对公开票、有无执照
 * 3. 上传营业执照图片
 * 4. 选择配送商信息
 * 5. 新增联系人信息
 */
public final class ConvertToTerminalActivity extends AppActivity
        implements ImageSelectActivity.OnPhotoSelectListener {

    // 线索信息
    private ImageView mLeadPhotoView;
    private TextView mLeadNameView;
    private TextView mLeadCodeView;
    private TextView mLeadAddressView;

    // 基本信息
    private TextView mCooperationStatusValue;
    private TextView mPaymentTypeValue;
    private TextView mTerminalTypeValue;

    // 营业执照
    private CheckBox mTaxInvoiceNoCheckBox;
    private CheckBox mTaxInvoiceYesCheckBox;
    private CheckBox mHasLicenseNoCheckBox;
    private CheckBox mHasLicenseYesCheckBox;
    private ImageView mLicensePhotoView;
    private ImageView mLicensePhotoDeleteView;
    private String mLicensePhotoPath;
    private TextView mLicensePhotoLabel;
    private EditText mRegisterNameEdit;
    private EditText mLicenseNumberEdit;

    // 配送商信息
    private TextView mDeliveryProviderValue;
    private TextView mSalespersonValue;
    private TextView mSalesAreaValue;
    private TextView mDepartmentValue;

    // 联系人信息
    private TextView mContactInfoLabel;
    private TextView mAddContactButton;

    // 提交按钮
    private TextView mSubmitButton;

    public static void start(Context context, String leadName) {
        Intent intent = new Intent(context, ConvertToTerminalActivity.class);
        intent.putExtra(IntentKey.NAME, leadName);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.convert_to_terminal_activity;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        // 线索信息
        mLeadPhotoView = findViewById(R.id.iv_lead_photo);
        mLeadNameView = findViewById(R.id.tv_lead_name);
        mLeadCodeView = findViewById(R.id.tv_lead_code);
        mLeadAddressView = findViewById(R.id.tv_lead_address);

        // 基本信息
        TextView cooperationStatusLabel = findViewById(R.id.tv_cooperation_status_label);
        mCooperationStatusValue = findViewById(R.id.tv_cooperation_status_value);
        TextView paymentTypeLabel = findViewById(R.id.tv_payment_type_label);
        mPaymentTypeValue = findViewById(R.id.tv_payment_type_value);
        TextView terminalTypeLabel = findViewById(R.id.tv_terminal_type_label);
        mTerminalTypeValue = findViewById(R.id.tv_terminal_type_value);

        // 营业执照
        TextView taxInvoiceLabel = findViewById(R.id.tv_tax_invoice_label);
        mTaxInvoiceNoCheckBox = findViewById(R.id.cb_tax_invoice_no);
        mTaxInvoiceYesCheckBox = findViewById(R.id.cb_tax_invoice_yes);
        TextView hasLicenseLabel = findViewById(R.id.tv_has_license_label);
        mHasLicenseNoCheckBox = findViewById(R.id.cb_has_license_no);
        mHasLicenseYesCheckBox = findViewById(R.id.cb_has_license_yes);
        mLicensePhotoView = findViewById(R.id.iv_license_photo);
        mLicensePhotoDeleteView = findViewById(R.id.iv_license_photo_delete);
        mLicensePhotoLabel = findViewById(R.id.tv_license_photo_label);
        TextView registerNameLabel = findViewById(R.id.tv_register_name_label);
        mRegisterNameEdit = findViewById(R.id.et_register_name);
        TextView licenseNumberLabel = findViewById(R.id.tv_license_number_label);
        mLicenseNumberEdit = findViewById(R.id.et_license_number);

        // 配送商信息
        TextView deliveryProviderLabel = findViewById(R.id.tv_delivery_provider_label);
        mDeliveryProviderValue = findViewById(R.id.tv_delivery_provider_value);
        TextView salespersonLabel = findViewById(R.id.tv_salesperson_label);
        mSalespersonValue = findViewById(R.id.tv_salesperson_value);
        TextView salesAreaLabel = findViewById(R.id.tv_sales_area_label);
        mSalesAreaValue = findViewById(R.id.tv_sales_area_value);
        TextView departmentLabel = findViewById(R.id.tv_department_label);
        mDepartmentValue = findViewById(R.id.tv_department_value);

        // 联系人信息
        mContactInfoLabel = findViewById(R.id.tv_contact_info);
        mAddContactButton = findViewById(R.id.btn_add_contact);

        // 提交按钮（使用内部按钮 ID）
        mSubmitButton = findViewById(R.id.tv_bottom_button);

        // 设置必填标记
        TextStarUtils.setRequiredText(cooperationStatusLabel, getString(R.string.cooperation_status));
        TextStarUtils.setRequiredText(paymentTypeLabel, getString(R.string.payment_type));
        TextStarUtils.setRequiredText(terminalTypeLabel, getString(R.string.terminal_type));
        TextStarUtils.setRequiredText(taxInvoiceLabel, "对公开票");
        TextStarUtils.setRequiredText(hasLicenseLabel, "有无执照");
        TextStarUtils.setRequiredText(mLicensePhotoLabel, "营业执照图");
        TextStarUtils.setRequiredText(registerNameLabel, getString(R.string.register_name));
        TextStarUtils.setRequiredText(licenseNumberLabel, getString(R.string.license_number));
        TextStarUtils.setRequiredText(deliveryProviderLabel, "配送商");
        TextStarUtils.setRequiredText(salespersonLabel, "业务员");
        TextStarUtils.setRequiredText(salesAreaLabel, getString(R.string.sales_area));
        TextStarUtils.setRequiredText(departmentLabel, "部门");
        TextStarUtils.setRequiredText(mContactInfoLabel, getString(R.string.contact_info));

        // 设置单选CheckBox的互斥逻辑
        setupCheckBoxGroup(mTaxInvoiceNoCheckBox, mTaxInvoiceYesCheckBox);
        setupCheckBoxGroup(mHasLicenseNoCheckBox, mHasLicenseYesCheckBox);

        // 设置营业执照图片点击事件
        mLicensePhotoView.setOnClickListener(v -> {
            ImageSelectActivity.start(this, 1, this);
        });

        // 设置图片删除按钮点击事件
        mLicensePhotoDeleteView.setOnClickListener(v -> deleteLicensePhoto());

        // 设置点击事件
        setOnClickListener(mCooperationStatusValue, mPaymentTypeValue, mTerminalTypeValue, 
                mDeliveryProviderValue, mAddContactButton, mSubmitButton);
    }

    @Override
    protected void initData() {
        // 获取Intent参数
        String leadName = getString(IntentKey.NAME);
        // 显示线索信息
        mLeadNameView.setText(leadName);

    }

    /**
     * 设置CheckBox互斥逻辑（单选，必须选中一个）
     * 
     * @param checkBox1 第一个CheckBox
     * @param checkBox2 第二个CheckBox
     */
    private void setupCheckBoxGroup(CheckBox checkBox1, CheckBox checkBox2) {
        checkBox1.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                // 选中checkBox1时，取消checkBox2
                checkBox2.setChecked(false);
            } else {
                // 尝试取消checkBox1时，如果checkBox2也是未选中状态，则强制选中checkBox1（必须选中一个）
                if (!checkBox2.isChecked()) {
                    checkBox1.setChecked(true);
                }
            }
        });

        checkBox2.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                // 选中checkBox2时，取消checkBox1
                checkBox1.setChecked(false);
            } else {
                // 尝试取消checkBox2时，如果checkBox1也是未选中状态，则强制选中checkBox2（必须选中一个）
                if (!checkBox1.isChecked()) {
                    checkBox2.setChecked(true);
                }
            }
        });
    }

    @SingleClick
    @Override
    public void onClick(View view) {
        super.onClick(view);
        int id = view.getId();
        if (id == R.id.tv_cooperation_status_value) {
            // 选择合作状态
            List<String> options = new ArrayList<>();
            options.add("合作中");
            options.add("终止合作");
            new SelectionListDialog.Builder(this)
                    .setTitle("请选择合作状态")
                    .setDataList(options)
                    .setListener(new SelectionListDialog.OnListener() {
                        @Override
                        public void onSelected(BaseDialog dialog, String selectedItem, int position) {
                            mCooperationStatusValue.setText(selectedItem);
                        }
                    })
                    .show();
        } else if (id == R.id.tv_payment_type_value) {
            // 选择付款类型
            List<String> options = new ArrayList<>();
            options.add("类型1");
            options.add("类型2");
            new SelectionListDialog.Builder(this)
                    .setTitle("请选择付款类型")
                    .setDataList(options)
                    .setListener(new SelectionListDialog.OnListener() {
                        @Override
                        public void onSelected(BaseDialog dialog, String selectedItem, int position) {
                            mPaymentTypeValue.setText(selectedItem);
                        }
                    })
                    .show();
        } else if (id == R.id.tv_terminal_type_value) {
            // 选择终端类型
            // 选择终端类型
            List<String> options = new ArrayList<>();
            options.add("超市");
            options.add("生鲜店");
            options.add("餐饮店");
            options.add("副食品店");
            options.add("水果店");
            options.add("企事业单位");
            options.add("早餐豆奶");
            options.add("农贸");
            options.add("预制菜");
            options.add("腐乳类");
            new SelectionListDialog.Builder(this)
                    .setTitle("请选择终端类型")
                    .setDataList(options)
                    .setListener(new SelectionListDialog.OnListener() {
                        @Override
                        public void onSelected(BaseDialog dialog, String selectedItem, int position) {
                            mTerminalTypeValue.setText(selectedItem);
                        }
                    })
                    .show();
        } else if (id == R.id.tv_delivery_provider_value) {
            // 选择配送商
            new SelectSubmitterDialog.Builder(this,101)//101 = 只显示配送商
                    .setListener(new SelectSubmitterDialog.OnListener() {
                        @Override
                        public void onSelected(BaseDialog dialog, String submitter, int type, Object data) {
                            // 显示选中的提交人
                            mDeliveryProviderValue.setText(submitter);
                            mDeliveryProviderValue.setTextColor(getResources().getColor(R.color.cb3));
                        }
                    })
                    .show();
        } else if (id == R.id.btn_add_contact) {
            // 新增联系人
            toast("新增联系人");
            // TODO: 打开新增联系人
        } else if (id == R.id.tv_bottom_button) {
            // 提交
            submitConvert();
        }
    }

    /**
     * 提交转终端
     */
    private void submitConvert() {
        // TODO: 验证必填项

        // 获取对公开票选择
        boolean isTaxInvoice = mTaxInvoiceYesCheckBox.isChecked();

        // 获取有无执照选择
        boolean hasLicense = mHasLicenseYesCheckBox.isChecked();

        // 获取注册名称
        String registerName = mRegisterNameEdit.getText().toString().trim();

        // 获取营业执照号
        String licenseNumber = mLicenseNumberEdit.getText().toString().trim();

        new TipsTwoDialog.Builder(getContext()).setTitle("确定转终端？").setListener(dialog -> {
            toast("提交");
        }).show();

    }

    /**
     * {@link ImageSelectActivity.OnPhotoSelectListener}
     * 图片选择回调
     */
    @Override
    public void onSelected(List<String> images) {
        if (images != null && !images.isEmpty()) {
            mLicensePhotoPath = images.get(0);
            updateLicensePhoto();
        }
    }

    @Override
    public void onCancel() {
        // 取消选择
    }

    /**
     * 更新营业执照图显示
     */
    private void updateLicensePhoto() {
        if (!TextUtils.isEmpty(mLicensePhotoPath) && new File(mLicensePhotoPath).exists()) {
            GlideApp.with(this)
                    .load(new File(mLicensePhotoPath))
                    .placeholder(R.drawable.add_ic)
                    .error(R.drawable.add_ic)
                    .into(mLicensePhotoView);
            mLicensePhotoView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            mLicensePhotoDeleteView.setVisibility(View.VISIBLE);
        } else {
            mLicensePhotoView.setImageResource(R.drawable.add_ic);
            mLicensePhotoView.setScaleType(ImageView.ScaleType.CENTER);
            mLicensePhotoDeleteView.setVisibility(View.GONE);
        }
    }

    /**
     * 删除营业执照照片
     */
    @SingleClick
    private void deleteLicensePhoto() {
        mLicensePhotoPath = null;
        updateLicensePhoto();
        toast("已删除营业执照照片");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 释放资源
    }
}

